<template>
  <van-nav-bar
    title="请假申请"
    left-text="返回"
    right-text="历史记录"
    left-arrow
    @click-left="onClickLeft"
    @click-right="onClickRight"
  />
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <!-- 类别 -->
      <van-field
        v-model="types"
        is-link
        readonly
        required
        name="请假类别"
        label="请假类别"
        placeholder="点击选择类别"
        @click="showPicker = true"
      />
      <van-popup v-model:show="showPicker" position="bottom">
        <van-picker
          :columns="columns"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>
      <!-- 开始时间 -->
      <van-field
        v-model="bTime"
        is-link
        readonly
        required
        name="开始时间"
        label="开始时间"
        placeholder="选择开始时间"
        @click="showTimePicker = true"
      />
      <van-popup v-model:show="showTimePicker" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          title="选择完整时间"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirmTime"
          @cancel="showTimePicker = false"
          :formatter="formatter"
        />
      </van-popup>
      <!-- 结束时间 -->
      <van-field
        v-model="eTime"
        is-link
        readonly
        required
        name="结束时间"
        label="结束时间"
        placeholder="选择结束时间"
        @click="showTimePicker1 = true"
      />
      <van-popup v-model:show="showTimePicker1" position="bottom">
        <van-datetime-picker
          v-model="currentDate1"
          type="datetime"
          title="选择完整时间"
          :min-date="minDate1"
          :max-date="maxDate1"
          @confirm="onConfirmTime1"
          @cancel="showTimePicker1 = false"
          :formatter="formatter"
        />
      </van-popup>
      <van-field
        v-model="phone"
        name="联系方式"
        label="联系方式"
        required
        placeholder="请输入手机号码"
        :rules="[{ validator, message: '请填写正确的手机号码' }]"
      />
      <van-field
        v-model="detail"
        required
        rows="2"
        autosize
        label="详情"
        name="详情"
        type="textarea"
        maxlength="50"
        placeholder="请输入请假详情"
        show-word-limit
        :rules="[{ required: true, message: '请输入请假详情' }]"
      />
      <van-cell>
        <van-uploader
          v-model="fileList"
          multiple
          :max-count="4"
          preview-size="68"
          name="photo"
        />
      </van-cell>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script lang="ts">
import axios from "axios";
import { ref } from "vue";
import {
  Button,
  Uploader,
  Dialog,
  Form,
  Field,
  CellGroup,
  NavBar,
  Picker,
  Popup,
  DatetimePicker,
  Toast,
} from "vant";
import { useRouter } from "vue-router";
// let forms = null; //设置公共变量，用来创建 FromData 对象，把文件带到后台
export default {
  // data() {
  //   return {
  //     //表单
  //     reportForm: {
  //       equipRepairNo: "", //数据库主键
  //       //...
  //       reportPic: "", //这个是数据库中存的路径，可以用来直接预览
  //     },
  //     //组件中绑定的照片属性
  //     reportPic: [],
  //   };
  // },
  // methods: {
  //   //提交表单
  //   onSubmit(values) {
  //     Dialog.confirm({
  //       title: "提示",
  //       message: "确认提交吗？",
  //     })
  //       .then(() => {
  //         //1.axios提交表单信息
  //         axios({
  //           method: "post",
  //           url: "/xxx/submit",
  //           data: this.reportForm,
  //         }).then((res) => {
  //           if (res.code == 200) {
  //             Toast.success(res.msg);
  //             this.reportForm.equipRepairNo = res.data;
  //             //2.表单提交完成后再提交图片信息
  //             this.reportPicUpload();
  //           } else {
  //             Toast.fail(res.msg);
  //           }
  //         });
  //       })
  //       .catch(() => {});
  //   },
  //   //图片选择后回调，这里就是重点了，就是在选择照片后，将照片的信息封装到FormData对象中
  //   //注意我这里是单图上传，所以直接new了，如果是多图的话，应该要考虑添加和删除FormData中的元素
  //   afterRead(file) {
  //     //创建FormData对象。上传图片需要转换二进制，这里要用到FormData
  //     forms = new FormData();
  //     //"file"表示给后台传的属性名字
  //     forms.append("file", file.file); //获取上传图片信息
  //   },
  //   //图片上传的前置处理
  //   beforeRead(file) {
  //     if (
  //       file.type !== "image/jpeg" ||
  //       file.type !== "image/jpg" ||
  //       file.type !== "image/png"
  //     ) {
  //       Toast("请上传图片格式");
  //       return false;
  //     }
  //     return true;
  //   },
  //   //图片删除前回调，删除时将公共变量forms中的文件信息一并删除
  //   beforeDelete(file) {
  //     forms = null;
  //     return true;
  //   },
  //   //图片上传，由提交按钮调用本方法实现手动上传
  //   reportPicUpload() {
  //     //如果文件列表为空，则不需要调用上传
  //     if (forms == null || forms.length == 0) {
  //       return;
  //     }
  //     axios({
  //       method: "post",
  //       url: "/xxx/reportPicUpload",
  //       data: forms,
  //       params: {
  //         equipRepairNo: this.reportForm.equipRepairNo,
  //       },
  //     })
  //       .then((res) => {
  //         if (res.code == 200) {
  //           Toast.success(res.msg);
  //           this.reportForm.reportPic = res.data;
  //           this.getRepairInfoByNo(this.reportForm.equipRepairNo);
  //         } else {
  //           Toast.fail(res.msg);
  //         }
  //       })
  //       .catch((err) => {
  //         Toast.fail("图片上传失败");
  //       });
  //   },
  // },
  watch: {
    $route() {
      window.location.reload();
    },
  },
  components: {
    [Button.name]: Button,
    [Uploader.name]: Uploader,
    [Dialog.name]: Dialog,
    [Form.name]: Form,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [NavBar.name]: NavBar,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [DatetimePicker.name]: DatetimePicker,
    [Toast.name]: Toast,
  },
  setup() {
    const $router = useRouter();
    const phone = ref("");
    const detail = ref("");
    const onSubmit = (values) => {
      console.log("submit", values);
      if (bTime.value < eTime.value) {
        console.log(fileList);
        Toast.success("提交成功");
        axios
          .post(
            "http://127.0.0.1:8088/addAttendance?end_time=" +
              eTime.value +
              "&start_time=" +
              bTime.value +
              "&phonenumber=" +
              phone.value +
              "&content=" +
              detail.value +
              "&attendance_type=" +
              types.value +
              "&photo_url=" +
              "",
            {
              // end_time: eTime.value,
              // start_time: bTime.value,
              // phonenumber: phone.value,
              // content: detail.value,
              // attendance_type: types.value,
              // photo_url: "dd"
            }
          )
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      } else {
        Dialog.alert({
          message: "开始时间必须小于结束时间\n提交失败",
        }).then(() => {
          // on close
        });
      }
    };
    // 校验函数返回 true 表示校验通过，false 表示不通过
    const validator = (val) =>
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
        val
      );
    const onClickRight = () => {
      $router.push({ path: "/about1" });
    };

    //请假类型
    const types = ref("事假");
    const showPicker = ref(false);
    const columns = ["事假", "病假"];
    const onConfirm = (value) => {
      types.value = value;
      showPicker.value = false;
    };
    //开始时间
    var date = new Date(); //获取时间
    const bTime = ref(date.toLocaleString());
    const eTime = ref(date.toLocaleString());
    const currentDate = ref(new Date());
    const currentDate1 = ref(new Date());
    const showTimePicker = ref(false);
    const showTimePicker1 = ref(false);
    //格式化时间
    const formatDate = (date) =>
      `${date.getFullYear()}/${
        date.getMonth() + 1
      }/${date.getDate()}/ ${date.getHours()}:${date.getMinutes()}`;
    const onConfirmTime = (value) => {
      bTime.value = formatDate(value);
      showTimePicker.value = false;
    };
    const onConfirmTime1 = (value) => {
      eTime.value = formatDate(value);
      showTimePicker1.value = false;
    };
    const formatter = (type, val) => {
      if (type === "year") {
        return `${val}年`;
      }
      if (type === "month") {
        return `${val}月`;
      }
      if (type === "day") {
        return `${val}日`;
      }
      if (type === "hour") {
        return `${val}时`;
      }
      if (type === "minute") {
        return `${val}分`;
      }
      return val;
    };

    const fileList = ref([]);

    return {
      validator,
      phone,
      detail,
      onSubmit,
      onClickRight,
      types,
      columns,
      onConfirm,
      showPicker,
      bTime,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate,
      currentDate1,
      onConfirmTime,
      onConfirmTime1,
      showTimePicker,
      showTimePicker1,
      formatter,
      eTime,
      fileList,
    };
  },
};
</script>

<style>
:root {
  --van-nav-bar-icon-color: white;
  --van-nav-bar-background-color: #00bfff;
  --van-nav-bar-text-color: white;
  --van-nav-bar-title-text-color: white;
}
</style>